package cn.topevery.garden.wapi.controller;

import cn.topevery.garden.dal.dao.impl.PlanCountDaoImpl;
import cn.topevery.garden.dal.dao.impl.PlanDaoImpl;
import cn.topevery.garden.dal.dao.impl.ScheduleDaoImpl;
import cn.topevery.garden.dal.logic.PlanLogic;
import cn.topevery.garden.dal.logic.ScheduleFileLogic;
import cn.topevery.garden.dal.logic.ScheduleLogic;
import cn.topevery.garden.dal.util.QueryWrapper;
import cn.topevery.garden.entity.dto.ScheduleDTO;
import cn.topevery.garden.entity.po.PlanCount;
import cn.topevery.garden.entity.po.Schedule;
import cn.topevery.garden.entity.po.ScheduleFile;
import cn.topevery.garden.entity.query.ScheduleQuery;
import cn.topevery.garden.entity.vo.ScheduleVO;
import com.github.dozermapper.core.Mapper;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.entity.KeyValue;
import hw.topevery.framework.util.ExcelUtil;
import hw.topevery.framework.web.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @author code-generate
 * @date 2022-02-16
 */
@Api(tags = "养护记录申报管理")
@RestController
@RequestMapping("/scheduleTask")
public class ScheduleController extends BaseController {

    @Autowired
    private Mapper mapper;

    @Autowired
    ScheduleLogic scheduleLogic;

    @Autowired
    ScheduleDaoImpl scheduleDao;

    @Autowired
    PlanCountDaoImpl planCountDao;

    @Autowired
    ScheduleFileLogic scheduleFileLogic;

    @Autowired
    private PlanLogic planLogic;

    @Autowired
    PlanDaoImpl planDao;

    /**
     * 获取分页列表
     *
     * @param query
     * @return
     */
    @ApiOperation(value = "获取页列表")
    @PostMapping("/getScheduleTaskList")
    public JsonResult<DataPager<ScheduleVO>> listPage(@RequestBody ScheduleQuery query) {
        DataPager<ScheduleVO> res = scheduleLogic.listPage(query);
        for (ScheduleVO scheduleVO : res.records) {
            List<ScheduleFile> list = scheduleFileLogic.getListByPid(scheduleVO.getId());
            scheduleVO.setFileList(list);
        }
        return JsonResult.ok(res);
    }

    @ApiOperation("新增/编辑 信息")
    @PostMapping("/saveOrUpdate")
    public JsonResult<Boolean> saveOrUpdate(@Valid @RequestBody ScheduleDTO dto) {
        dto.setFlowState(1);
        dto.setType(1);
        String userId = getUser().id.toString();
        Schedule schedule = mapper.map(dto, Schedule.class);
        scheduleLogic.saveOrUpdate(userId, schedule);
        //保存附件
        scheduleFileLogic.saveOrUpdate(userId, schedule.getId(), schedule.getFileList());
        Map<String, Object> countList = planCountDao.getCountList(dto.getScheduleName());
        PlanCount entityByColumn = planCountDao.getEntityByColumn("c_section_id", countList.get("sectionId").toString());
        if (entityByColumn == null) {
            PlanCount planCount = new PlanCount();
            planCount.setSectionId(countList.get("sectionId").toString());
            planCount.setSectionName(countList.get("sectionName").toString());
            planCount.setUsePay(Double.parseDouble(countList.get("val").toString()));
            planCountDao.insert(getUser().id.toString(), planCount);
        } else {
            planCountDao.updateByTable(getUser().id.toString(), new QueryWrapper<KeyValue>().
                            eq("c_use_pay", Double.parseDouble(countList.get("val").toString()))
                    , new QueryWrapper<>().where("c_section_id", countList.get("sectionId").toString()));
        }

        //更新养护任务的执行时间
        planLogic.updateExecuteDate(dto);

        return JsonResult.ok(true);
    }

    @ApiOperation("通过Id获取详情")
    @GetMapping("/getInfoById")
    public JsonResult<ScheduleVO> getInfoById(@RequestParam Integer id) {
        Schedule entity = scheduleLogic.getEntity(id);
        entity.setFileList(scheduleFileLogic.getListByPid(id));
        ScheduleVO vo = mapper.map(entity, ScheduleVO.class);
        return JsonResult.ok(vo);
    }

    @ApiOperation("根据自增ID批量删除")
    @PostMapping("/deleteBatchById")
    public JsonResult<Boolean> deleteBatchById(@RequestBody Integer[] ids) {
        Integer userId = getUser().id;
        scheduleLogic.deleteBatchById(userId.toString(), ids);
        scheduleFileLogic.deleteBatchByGuid(userId, ids);
        return JsonResult.ok(true);
    }

    @ApiOperation("导出信息")
    @GetMapping("/export")
    public void export(ScheduleQuery query, HttpServletResponse response) {
        List<ScheduleVO> list = scheduleLogic.listPage(query).records;
        ExcelUtil.exportExcel(list, "", "sheet1", ScheduleVO.class, "", response);
    }

    @ApiOperation("审核")
    @PostMapping("/updateState")
    public JsonResult updateState(@RequestBody ScheduleDTO dto) {
        scheduleDao.updateByTable(getUser().id.toString(), new QueryWrapper<KeyValue>()
                        .eq("c_flow_state", dto.getFlowState())
                        .eq("c_result", dto.getResult())
                        .eq("c_suggest", dto.getSuggest())
                        .eq("c_check_time", LocalDateTime.now())
                        .eq("c_checker_id", getUser().id),
                new QueryWrapper()
                        .where("c_id", dto.getId()));
        //更新养护任务状态
        if (dto.getResult() == 1) {
            planDao.updateByTable(getUser().id.toString(), new QueryWrapper<>()
                    .eq("c_state", 3), new QueryWrapper<>().where("c_plan_id", dto.getScheduleId()));
        }
        return JsonResult.ok(true);
    }

    @ApiModelProperty("抽查")
    @PostMapping("/updateType")
    public JsonResult updateType(@RequestBody ScheduleDTO dto) {
        if (dto.getId() != null) {
            scheduleDao.updateByTable(getUser().id.toString(), new QueryWrapper<KeyValue>()
                            .eq("c_type", dto.getType())
                            .eq("c_sample_desc", dto.getSampleDesc()),
                    new QueryWrapper<KeyValue>()
                            .where("c_id", dto.getId()));
            scheduleFileLogic.saveSampleFile(getUser().id.toString(), dto.getId(), dto.getSampleFileList());
        } else {
            scheduleDao.updateType(dto);
        }
        return JsonResult.ok(true);
    }

    @ApiOperation("获取统计数据")
    @PostMapping("/getMonth")
    public JsonResult getMonth() {
        return JsonResult.ok(scheduleDao.getMonth());

    }

    @ApiOperation("获取抽查记录")
    @PostMapping("/getSampleRecord")
    public JsonResult<DataPager<ScheduleVO>> getSampleRecord(@RequestBody ScheduleQuery query) {
        return JsonResult.ok(scheduleLogic.getSampleRecord(query));
    }

}
